﻿/*

//DEMO:

//<script type="text/javascript">
//    var dataGridControl;
//    $(document).ready(function() {
//                        //参数说明：表格所处DIV ID，表格宽   表格所在滚动容器     XML数据源
//        dataGridControl = CreateDataGrid("dataGrid", 1200, "contentArea", "/StyleSample/DataSource");
//    });
//</script>
//<div class="junpTable" id="dataGrid"></div>

*/


function CreateDataGrid(controlId, controlWidth, scrollContinerId, dataSourceUrl) {
    showWatting();
    var dataGrid = new DataGrid(controlId, controlWidth, scrollContinerId);
    //dataGrid.DebugMode = true;
    $.ajax({ url: dataSourceUrl, type: "GET", dataType: "xml", cache: false,
        error: function() { alert('Error'); hideWatting(); }, success: function(xml) {
            dataGrid.loadDataSourceFinish(xml);
        }
    });
    return dataGrid;
}

function DataGrid(controlId, controlWidth, scrollContinerId) {
    var dg = new Object();

    dg.controlId = controlId;
    dg.arrowIcon = "/images/arrowIcon.gif";
    dg.lockCount = 0;
    dg.scrollContinerId = scrollContinerId;
    dg.SelectMode = "None";
    dg.IsBuildEmptyRow = false;
    dg.MinRowCount = 0;    
    dg.GroupsCss = new Array();
    dg.GroupsCss[0] = "vitta_bule";
    dg.GroupsCss[1] = "vitta_green";
    dg.GroupsCss[2] = "vitta_yellow";
    dg.GroupsCss[3] = "vitta_pink";
    dg.GroupsCss[4] = "vitta_smalt";
    dg.tableThColors = new Array();
    dg.tableThColors[0] = '#b7e1f6';
    dg.tableThColors[1] = '#b2d871';
    dg.tableThColors[2] = '#20b4e2';
    dg.tableThColors[3] = '#6666cc';
    dg.tableThColors[4] = '#33cccc';
    dg.offset = new Object();
    dg.offset.Top = 0;
    dg.offset.Left = 0;
    dg.CurrentHeadStat = 0;  // 表头状态 0:float  1:inTable
    dg.ShowOverToolPanel = false;   //是否启动浮动工具栏
    dg.DebugMode = false;
    dg.PageControl = new Object();
    dg.PageControl.Show = false;
    dg.PageControl.PageIndex = 0;
    dg.PageControl.PageSize = 0;
    dg.PageControl.RecordCount = 0;
    dg.PageControl.PageCount = 0;
    dg.PageControl.CurrPageView = 0;
    dg.PageControl.PageViewCount = 0;
    dg.PageControl.PageUrl = "";
    dg.LoadFinish = false;

    var dataGrid = $("#" + controlId);
    dataGrid.width(controlWidth);
    dataGrid.html("<div class='initPanel'>初始化中....</div>");

    dg.CreateElement = function(tagName, className) {
        var element = document.createElement(tagName);
        element.className = className;
        return element;
    }

    //GridEnterPoint
    dg.loadDataSourceFinish = function(xml) {
        var time1 = new Date();

        var dataGrid = $("#" + controlId);
        dataGrid.html("");
        {
            var tableBigHeadDiv = dg.CreateElement("div", "tableBigHead");
            tableBigHeadDiv.appendChild(dg.CreateElement("div", "tableCaption"));
            var tableHeadDiv = dg.CreateElement("div", "tableHead");
            tableHeadDiv.appendChild(dg.CreateElement("div", "lockTableHead"));
            tableHeadDiv.appendChild(dg.CreateElement("div", "scrollTableHead"));
            tableBigHeadDiv.appendChild(tableHeadDiv);
            dataGrid.append(tableBigHeadDiv);

            var tableBodyDiv = dg.CreateElement("div", "tableBody");
            tableBodyDiv.appendChild(dg.CreateElement("div", "lockTableBody"));
            tableBodyDiv.appendChild(dg.CreateElement("div", "scrollTableBody"));
            dataGrid.append(tableBodyDiv);

            if (dg.DebugMode) {
                var debugDiv = dg.CreateElement("div", "");
                debugDiv.id = "debug";
                debugDiv.style.position = "absolute";
                debugDiv.style.left = 0;
                debugDiv.style.top = 0;
                debugDiv.innerHTML = "DataGrid Debug Panel";
                dataGrid.append(debugDiv);
            }
        }

        var tableBigHead = dataGrid.find(".tableBigHead");
        tableBigHead.width(dataGrid.width() - 2);
        var tableBody = dataGrid.find(".tableBody");
        tableBody.width(dataGrid.width() - 2);

        var Groups = $(xml).find("DataGrid > Schema > Groups > Group");
        var info = $(xml).find("DataGrid > Schema > Informattion");
        dg.IsBuildEmptyRow = info.attr("AddEmptyRow") == "True";
        if (dg.IsBuildEmptyRow) {
            dg.MinRowCount = parseInt(info.attr("MinRowCount"));
        }
        dg.CreateCaptionTable(Groups, info);
        Groups.each(function(i, o) {
            if (i == 0) dg.CreateLockTableHead(o);
            else {
                dg.groupsPropertyCountArray[i - 1] = dg.CreateScrollTableHead(i, o);
            }
        });
        var page = $(xml).find("DataGrid > Schema > Informattion > Page");
        if (page.size() == 1) {
            dg.PageControl.Show = true;
            dg.initPageControl(page);
        }
        dg.CreateTableBody($(xml).find("DataGrid > DataSouce"));
        if (dg.IsBuildEmptyRow) {
            dg.CreateEmptyRecord();
        }
        dg.BuildStyle();

        var tableHeadDom = $$(dg.controlId).getElementsByTagName("div")[0];
        var obj = tableHeadDom;
        while (obj != null) { dg.offset.Top += obj.offsetTop; dg.offset.Left += obj.offsetLeft; obj = obj.offsetParent; }
        var top = dg.offset.Top;
        var tableHead = $("#" + dg.controlId).find(".tableBigHead");
        tableHead.attr("_minTop", top);
        tableHead.attr("_maxTop", top + $("#" + dg.controlId).find(".tableBody").height() - $("#" + dg.controlId + "_scrollTableBody").find("tbody > tr:last").height());
        $("#" + scrollContinerId).scroll(dg.onScroll);
        dg.setArrowIcon();
        dg.onScroll();
        if (dg.ShowOverToolPanel) dg.initOverToolPanel();

        dg.LoadFinish = true;
        hideWatting();

        var run = new Date() - time1;
        dg.debugMsg("loadTime: " + run);
    }

    dg.GetSelectId = function() {
        return $("input[name='" + dg.controlId + "_record'][@checked]:first").val();
    }

    dg.GetSelectIds = function() {
        var selectIds = new Array();
        $("input[name='" + dg.controlId + "_record'][@checked]").each(function(i, o) {
            selectIds[i] = $(o).val();
        });
        return selectIds;
    }

    ///浮动工具版面开始
    dg.initOverToolPanel = function() {
        var toolPanel = document.createElement("div");
        toolPanel.id = dg.controlId + "_OTP";
        var hlImg = document.createElement("img");
        hlImg.src = "/images/highlight.gif";
        hlImg.alt = "高亮显示记录";
        var hlLink = document.createElement("a");
        hlLink.onclick = dg.HightLight_OnClick;
        hlLink.appendChild(hlImg);
        toolPanel.appendChild(hlLink);
        $("#" + dg.controlId).append(toolPanel);

        var panel = $("#" + dg.controlId + "_OTP");
        panel.css("position", "absolute");
        panel.css("display", "none");
        panel.attr("class", "OTP");
        //panel.mouseover(dg.OTP_P_MouseOver);
        //panel.mouseout(function() { $("#" + dg.controlId + "_OTP").hide(); });

        $("#" + dg.controlId + "_lockTableBody").find("tbody > tr").each(function(i, tr) {
            $(tr).mousedown(dg.OTP_MouseMove);
            //$(tr).mouseover(dg.OTP_MouseOver);
            //$(tr).mouseout(dg.OTP_MouseOut);
        });
        $("#" + dg.controlId + "_scrollTableBody").find("tbody > tr").each(function(i, tr) {
            $(tr).mousedown(dg.OTP_MouseMove);
            //$(tr).mouseover(dg.OTP_MouseOver);
            //$(tr).mouseout(dg.OTP_MouseOut);
        });
    }

    dg.OTP_MouseOver = function(event) {
        if (dg.isMoving) return;
        dg.debugMsg("cX:" + event.clientX + "|xY:" + event.clientY);
    }

    dg.OTP_MouseMove = function(event) {
        if (dg.isMoving) return;
        var guid = $(this).find("input").attr("value");
        if (guid == "" || guid == null || guid == 'undefined') return;
        //dg.debugMsg("mouseMove:" + guid);
        var panel = $("#" + dg.controlId + "_OTP");
        panel.hide();
        panel.attr("_record", guid);
        panel.css("top", event.clientY - 5);
        panel.css("left", event.clientX + 10);
        panel.show(200, null);
    }
    dg.OTP_P_MouseOver = function(event) {
        var panel = $("#" + dg.controlId + "_OTP");
        panel.show();
    }
    dg.OTP_MouseOut = function(event) {
        if (dg.isMoving) return;
        var panel = $("#" + dg.controlId + "_OTP");
        panel.hide();
        dg.debugMsg("mouseOut:" + $(this).find("input").attr("value"));
    }

    dg.HightLight_OnClick = function(event) {
        var panel = $("#" + dg.controlId + "_OTP");
        var guid = panel.attr("_record");
        $("#" + dg.controlId + "_lt" + guid).find("td").each(function(i, o) {
            var curr = $(o).attr("class");
            $(o).attr("class", curr == "highLightTr" ? "norTr" : "highLightTr");
        });
        $("#" + dg.controlId + "_rt" + guid).find("td").each(function(i, o) {
            var curr = $(o).attr("class");
            $(o).attr("class", curr == "highLightTr" ? "norTr" : "highLightTr");
        });
        panel.hide(200, function() { });
    }

    ///浮动工具版面结束


    //表格在滚动
    dg.onScroll = function() {
        var content = $$(dg.scrollContinerId);
        var tableHead = $("#" + dg.controlId).find(".tableBigHead");
        var tableBody = $("#" + dg.controlId).find(".tableBody");

        var msg = "";
        var maxTop = tableHead.attr("_maxTop");
        var minTop = tableHead.attr("_minTop");
        var sTop = content.scrollTop;
        var arrow = $("#" + dg.controlId + "_move");

        var toolBarHeight = $(".Toolbar").height();
        if (minTop - (sTop + toolBarHeight) < 0 && (sTop + toolBarHeight) < maxTop) {
            tableHead.css("position", "absolute");
            tableBody.css("padding-top", tableHead.height());
            tableHead.css("top", toolBarHeight);
            if (dg.CurrentHeadStat != 1) {
                arrow.attr("_minLeft", parseInt(arrow.attr("_minLeft")) - dg.offset.Left);
                arrow.attr("_maxLeft", parseInt(arrow.attr("_maxLeft")) - dg.offset.Left);
                arrow.css("left", parseInt(arrow.css("left")) - dg.offset.Left);
                dg.CurrentHeadStat = 1;
            }
            arrow.show();
            arrow.css("top", parseInt(arrow.attr("_absTop")));
            msg = "滚表头 并还在显示区域内";
        } else {
            tableHead.css("position", "static");
            tableHead.css("top", 0);
            tableBody.css("padding-top", "0");
            if (dg.CurrentHeadStat != 0) {
                arrow.attr("_minLeft", parseInt(arrow.attr("_minLeft")) + dg.offset.Left);
                arrow.attr("_maxLeft", parseInt(arrow.attr("_maxLeft")) + dg.offset.Left);
                arrow.css("left", parseInt(arrow.css("left")) + dg.offset.Left);
                dg.CurrentHeadStat = 0;
            }
            var screentHeight = $("#" + dg.scrollContinerId).height() + $(".Toolbar").height() - 1;
            var crrTop = parseInt(tableHead.attr("_minTop")) + parseInt(arrow.attr("_absTop")) - sTop - 1;
            if (sTop < maxTop && crrTop < screentHeight) {
                arrow.show();
                arrow.css("top", crrTop);
                msg = "在屏幕中滚";
            } else {
                arrow.hide();
                msg = "屏幕外";
            }
        }
        var debug = $("#debug");
        debug.html(msg + ":" + content.scrollTop + ":" + content.scrollLeft + "|" + tableHead.attr("_minTop") + ":" + tableHead.attr("_maxTop"));
    }

    //初始化滑动箭头
    dg.setArrowIcon = function() {
        var tableCaption = $("#" + dg.controlId).find(".tableBigHead > .tableCaption");
        var arrowDiv = document.createElement("div");
        arrowDiv.id = dg.controlId + "_move";
        arrowDiv.style.position = "absolute";
        arrowDiv.style.cursor = "e-resize";
        var arrowImg = document.createElement("img");
        arrowImg.src = dg.arrowIcon;
        arrowImg.alt = "拖动显示表格内容";
        arrowDiv.appendChild(arrowImg);
        tableCaption.append(arrowDiv);
        $("#" + dg.controlId + "_move").mousedown(dg.move_OnMouseDown);
        $("#" + dg.controlId + "_move").mouseup(dg.move_OnMouseUp);
        $(document).mousemove(dg.OnMouseMoving);

        dg.setArrowIconVar();
    }

    dg.setArrowIconVar = function() {
        var arrow = $("#" + dg.controlId + "_move");
        var table = $("#" + dg.controlId).find(".tableBigHead > .tableCaption > table");
        var leftTr = table.find("tbody > tr:first > td:first");
        arrow.attr("_minLeft", leftTr.width() + $("#" + dg.controlId + "_move").find("img").width() + dg.offset.Left);
        arrow.css("left", arrow.attr("_minLeft"));
        var leftTr2 = table.find("tbody > tr:first > td:eq(1)");
        arrow.attr("_maxLeft", leftTr.width() + leftTr2.width() + dg.offset.Left);

        var topTd = table.find("tbody > tr:first > td:eq(1)");
        arrow.attr("_absTop", topTd.height() + 5);
        arrow.css("top", (parseInt(arrow.attr("_absTop")) + parseInt($("#" + dg.controlId + " .tableBigHead").attr("_minTop"))));

        var offW = $$(dg.controlId + "_scrollTableHead").parentNode.offsetWidth;
        var scrollDivWidth = $("#" + dg.controlId).find(".scrollTableHead > table").width();
        var viewOffSet = (arrow.attr("_maxLeft") - arrow.attr("_minLeft")) * (arrow.attr("_maxLeft") - arrow.attr("_minLeft")) / scrollDivWidth;
        arrow.attr("_viewOffSet", viewOffSet);    
    }

    dg.BuildStyle = function() {
        dg.scrollCellWidth();
        dg.scrollCellHeight();
    }

    dg.groupsTotalWidth = 0;
    dg.groupsPropertyCountArray = new Array();
    dg.groupsWidthArray = new Array();
    dg.scrollCellWidth = function() {
        //设置LockTable各列宽度
        {
            var lockCellWidth = new Array();
            var head = $$(dg.controlId + "_lockTableHead").rows[0];
            var body = $$(dg.controlId + "_lockTableBody").rows[0];
            var totalWidth = 0;
            for (var i = 0; i < head.cells.length; i++) {
                var max = Math.max(head.cells[i].clientWidth, body.cells[i].clientWidth) + 10;
                lockCellWidth[i] = max;
                totalWidth += max;
            }
            for (var i = 0; i < head.cells.length; i++) {
                head.cells[i].style.width = parseFloat(lockCellWidth[i] / totalWidth * 100) + "%";
                body.cells[i].style.width = parseFloat(lockCellWidth[i] / totalWidth * 100) + "%";
            }
            $$(dg.controlId + "_lockTableHead").style.width = "100%";
            $$(dg.controlId + "_lockTableBody").style.width = "100%";
        }
        var currGroupIndex = 0;
        var cc = 0;
        dg.groupsWidthArray[0] = 0;
        //DOM方法设置滚动单元格宽
        {
            var head = $$(dg.controlId + "_scrollTableHead").rows[0];
            var body = $$(dg.controlId + "_scrollTableBody").rows[0];
            for (var i = 0; i < head.cells.length; i++) {
                var max = Math.max(head.cells[i].clientWidth, body.cells[i].clientWidth) + 75;
                head.cells[i].style.width = max;
                body.cells[i].style.width = max;
                dg.groupsTotalWidth += max;

                if (dg.groupsPropertyCountArray[currGroupIndex] < cc) {
                    cc = 0;
                    currGroupIndex++;
                    dg.groupsWidthArray[currGroupIndex] = 0;
                }
                cc++;
                dg.groupsWidthArray[currGroupIndex] += max;
            }
        }
        //设置View单元格宽
        {
            var tdtmp = $("#" + dg.controlId).find(".tableBigHead > .tableCaption > table > tbody > tr:eq(0) > td:eq(1)");
            var totalWidth = tdtmp.width();
            var tds = $("#" + dg.controlId).find(".tableBigHead > .tableCaption > table > tbody > tr:eq(1) > td");
            tds.each(function(i, o) {
                var currWidth = dg.groupsWidthArray[i];
                var width = totalWidth * parseInt(dg.groupsWidthArray[i]) / dg.groupsTotalWidth;
                $(o).attr("class", dg.GroupsCss[i % 5]);
                $(o).width(width);
            });
        }
        //设置2个滚动表格等宽
        {
            var head = $("#" + dg.controlId + "_scrollTableHead");
            var body = $("#" + dg.controlId + "_scrollTableBody");
            head.width(dg.groupsTotalWidth);
            body.width(dg.groupsTotalWidth);
        }
    }

    dg.scrollCellHeight = function() {
        //设置Lock与Socroll的行高相等
        {
            var lock = $("#" + dg.controlId + "_lockTableBody");
            var scrollBody = $("#" + dg.controlId + "_scrollTableBody");
            var totalHeight = 0;
            lock.find("tbody > tr").each(function(i, o) {
                scrollBody.find("tbody > tr:eq(" + i + ")").height($(o).height());
            });
        }
    }

    //创建锁定列表头表格
    dg.CreateLockTableHead = function(o) {
        var table = document.createElement("table");
        table.cellPadding = 0;
        table.cellSpacing = 1;
        table.border = 0;
        table.id = dg.controlId + "_lockTableHead";
        var th = table.insertRow(0);
        if (dg.SelectMode != "None") {
            if (dg.SelectMode == "Mulit") {
                var checkAllCtl = document.createElement("input");
                checkAllCtl.id = dg.controlId + "_CheckAll";
                checkAllCtl.type = "checkbox";
                checkAllCtl.onclick = function() {
                    var result = $("#" + dg.controlId + "_CheckAll").attr("checked");
                    var tmp = $("input[name='" + dg.controlId + "_record']");
                    tmp.each(function(i, checkBox) {
                        $(checkBox).attr("checked", result);
                    });
                };
                th.insertCell().appendChild(checkAllCtl);
            } else th.insertCell().innerHTML = "&nbsp;";
        }
        var idx = th.insertCell();
        idx.innerHTML = "序号";
        $(o).find("property").each(function(i, item) {
            var cell = th.insertCell();
            cell.innerHTML = $(item).attr("propertyName");
            dg.lockCount++;
        });
        $("#" + dg.controlId).find(".tableHead > .lockTableHead").html(table);
    }

    //创建滚动列表头表格
    dg.CreateScrollTableHead = function(i, o) {
        var table;
        var th;
        if (i == 1) {
            table = document.createElement("table");
            table.cellPadding = 0;
            table.cellSpacing = 1;
            table.border = 0;
            table.id = dg.controlId + "_scrollTableHead";
            th = table.insertRow(0);
            $("#" + dg.controlId).find(".tableBigHead > .tableHead > .scrollTableHead").html(table);
        } else {
            table = document.getElementById(dg.controlId + "_scrollTableHead");
            th = table.rows[0];
        }

        var captionCell = $("#" + dg.controlId).find(".tableBigHead > .tableCaption > table > tbody > tr:first > td:eq(1)");
        var aLink = document.createElement("a");
        aLink.onclick = function() { dg.ScrollToGroupStartProperty(i - 1) };
        var captionImg = document.createElement("img");
        captionImg.src = "/images/vitta_" + ((i - 1) % 5 + 1) + ".jpg";
        aLink.appendChild(captionImg);
        aLink.innerHTML += "&nbsp;" + $(o).attr("groupName") + "&nbsp;&nbsp;";
        captionCell.append(aLink);
        captionCell.attr("class", "TitleTabR");

        var propertyCount = 0;
        $(o).find("property").each(function(pIndex, item) {
            var cell = th.insertCell();
            cell.innerHTML = "<nobr>" + $(item).attr("propertyName") + "</nobr>";
            cell.style.backgroundColor = dg.tableThColors[(i - 1) % 5];
            propertyCount++;
        });
        return propertyCount;
    }

    //创建DataGrid内容
    dg.CreateTableBody = function(o) {
        dg.CreateTableBodyTable();
        $(o).find("DataItem").each(function(pIndex, dataItem) {
            var pk = $(dataItem).attr("PrimaryKey");
            dg.CreateLockTableBody(pIndex, dataItem, pk);
            dg.CreateScrollTableBody(dataItem, pk, pIndex == 0);
        });        
    }

    //创建固定列内容
    dg.CreateLockTableBody = function(idx, o, pk) {
        var table = document.getElementById(dg.controlId + "_lockTableBody");
        var th = table.insertRow(table.rows.length);
        th.id = dg.controlId + "_lt" + pk;

        if (dg.SelectMode != "None") {
            var cell0 = th.insertCell();
            cell0.className = "norTr";
            var ctl = document.createElement("input");
            switch (dg.SelectMode) {
                case "Single":
                    if (document.uniqueID) {
                        ctl = document.createElement("<input type=\"radio\" name=\"" + dg.controlId + "_record\" value=\"" + pk + "\" />");
                    } else ctl.type = "radio";
                    break;
                case "Mulit":
                    ctl.type = "checkbox";
                    break;
                default:
                    ctl.type = "hidden";
                    break;
            }
            
            ctl.value = pk;
            ctl.name = dg.controlId + "_record";
        
            cell0.appendChild(ctl);
        }
        var cell1 = th.insertCell();
        cell1.className = "norTr";
        //alert((dg.PageControl.PageIndex * dg.PageControl.PageSize) + (idx + 1));
        cell1.innerHTML = (dg.PageControl.PageIndex * dg.PageControl.PageSize) + (idx + 1);
        $(o).find("data").each(function(i, data) {
            if (i >= dg.lockCount) return;
            var cell = th.insertCell();
            cell.innerHTML = "";
            if (i == 0 && dg.SelectMode == "None") {
                var ctl = document.createElement("input");
                ctl.type = "hidden";
                ctl.value = pk;
                cell.appendChild(ctl);
            }
            cell.className = "norTr";
            cell.innerHTML += $(data).attr("dataValue");
        });
    }

    //创建滚动列内容
    dg.CreateScrollTableBody = function(o, pk, createTdId) {
        var table = document.getElementById(dg.controlId + "_scrollTableBody");
        var th = table.insertRow(table.rows.length);
        th.id = dg.controlId + "_rt" + pk;
        var isFirstLoad = true;
        $(o).find("data").each(function(i, data) {
            if (i >= dg.lockCount) {
                var cell = th.insertCell();
                if (isFirstLoad) {
                    var hidePk = document.createElement("input");
                    hidePk.type = "hidden";
                    hidePk.value = pk;
                    cell.appendChild(hidePk);
                    isFirstLoad = false;
                }
                cell.className = "norTr";
                if (createTdId) cell.id = "lr" + i;
                var noBr = document.createElement("nobr");
                noBr.innerHTML = $(data).attr("dataValue");
                cell.appendChild(noBr);
            }
        });
    }

    dg.isMoving = false;
    dg.move_OnMouseDown = function() {
        dg.isMoving = true;
        $$(dg.controlId + "_move").setCapture();
    }

    dg.move_OnMouseUp = function() {
        dg.isMoving = false;
        $$(dg.controlId + "_move").releaseCapture();
    }

    dg.OnMouseMoving = function(event) {
        if (!dg.isMoving) return;

        var arrow = $("#" + dg.controlId + "_move");
        var arrowMinLeft = parseInt(arrow.attr("_minLeft"));
        var arrowMaxLeft = parseInt(arrow.attr("_maxLeft"));
        if (event.clientX < arrowMinLeft) {
            arrow.css("left", arrowMinLeft);
            dg.ScrollTableToPx(0);
            return;
        }
        if (event.clientX > arrowMaxLeft) {
            arrow.css("left", arrowMaxLeft);
            dg.ScrollTableTo(1);
            return;
        }

        var viewOffSet = parseInt($("#" + dg.controlId + "_move").attr("_viewOffSet"));
        var currP = (event.clientX - arrowMinLeft + viewOffSet) / (arrowMaxLeft - arrowMinLeft + viewOffSet);
        var p = currP * $("#" + dg.controlId).find(".scrollTableHead > table").width();
        dg.ScrollTableToPx(p);
        arrow.css("left", (event.clientX - arrow.find("img").width() / 2 - (dg.CurrentHeadStat == 0 ? 0 : dg.offset.Left)));
    }

    dg.debugMsg = function(msg) {        
        $("#debug").html(msg);
    }

    //创建CaptionTable
    dg.CreateCaptionTable = function(Groups, info) {
        var captionTable = document.createElement("table");
        captionTable.cellPadding = 0;
        captionTable.cellSpacing = 0;
        captionTable.border = 0;
        var row1 = captionTable.insertRow();
        var r1c1 = row1.insertCell();
        r1c1.style.width = "30%";
        r1c1.rowSpan = 2;
        r1c1.className = "TitleTabL";
        var headImg = document.createElement("img");
        headImg.src = "/images/contractInfoImg.jpg";
        headImg.alt = info.attr("Caption");
        dg.SelectMode = info.attr("SelectMode");
        dg.ShowOverToolPanel = info.attr("ShowOverToolPanel") == "True";
        r1c1.appendChild(headImg);
        var headCaptionDiv = document.createElement("div");
        headCaptionDiv.innerHTML = info.attr("Caption");
        headCaptionDiv.className = "TitleTab";
        r1c1.appendChild(headCaptionDiv);
        var r1c2 = row1.insertCell();
        r1c2.colSpan = Groups.size() - 1;
        r1c2.className = "TitleTabR";
        var row2 = captionTable.insertRow();
        for (var i = 1; i < Groups.size(); i++) {
            var cell = row2.insertCell();
            cell.innerHTML = "&nbsp;";
            cell.style.backgroundColor = dg.tableThColors[(i - 1) % 5];
            cell.onmousedown = function() {
                dg.isMoving = true;
                dg.OnMouseMoving(event);
                dg.isMoving = false;
            };
        }
        var tableCaption = $("#" + dg.controlId).find(".tableBigHead > .tableCaption");
        tableCaption.append(captionTable);
    }

    //创建空表身
    dg.CreateTableBodyTable = function() {
        var table = document.createElement("table");
        table.cellPadding = 0;
        table.cellSpacing = 1;
        table.border = 0;
        table.id = dg.controlId + "_lockTableBody";
        $("#" + dg.controlId).find(".tableBody > .lockTableBody").html(table);

        var table2 = document.createElement("table");
        table2.id = dg.controlId + "_scrollTableBody";
        table2.cellPadding = 0;
        table2.cellSpacing = 1;
        table2.border = 0;
        $("#" + dg.controlId).find(".tableBody > .scrollTableBody").html(table2);
    }

    dg.ScrollTableTo = function(percent) {
        var to = $$(dg.controlId + "_scrollTableHead").parentNode.scrollWidth * percent;
        $$(dg.controlId + "_scrollTableHead").parentNode.scrollLeft = to;
        $$(dg.controlId + "_scrollTableBody").parentNode.scrollLeft = to;
    }

    dg.ScrollTableToPx = function(to) {
        var offW = $$(dg.controlId + "_scrollTableHead").parentNode.offsetWidth;
        $$(dg.controlId + "_scrollTableHead").parentNode.scrollLeft = to - offW;
        $$(dg.controlId + "_scrollTableBody").parentNode.scrollLeft = to - offW;
    }

    dg.ScrollToGroupStartProperty = function(groupIndex) {
        var px = 0;
        for (var i = 0; i < groupIndex; i++) {
            px += dg.groupsWidthArray[i];
        }
        dg.ScrollTableToPx(px);
        dg.RefreshArrowPoint();
    }

    //重定位滚动条指针
    dg.RefreshArrowPoint = function() {
        var offW = $$(dg.controlId + "_scrollTableHead").parentNode.offsetWidth;
        var px = $$(dg.controlId + "_scrollTableHead").parentNode.scrollLeft + offW;
        var arrow = $("#" + dg.controlId + "_move");
        var viewOffSet = parseInt($("#" + dg.controlId + "_move").attr("_viewOffSet"));
        var arrowMinLeft = parseInt(arrow.attr("_minLeft"));
        var arrowMaxLeft = parseInt(arrow.attr("_maxLeft"));
        var currP = px / $("#" + dg.controlId).find(".scrollTableHead > table").width();
        var clientX = currP * (arrowMaxLeft - arrowMinLeft + viewOffSet) + (arrowMinLeft - viewOffSet);
        if (px == 0) clientX = arrowMinLeft;
        arrow.css("left", (clientX - arrow.find("img").width() / 2) + "px");
    }

    //分页控件
    dg.initPageControl = function(pageInfo) {
        dg.PageControl.PageIndex = parseInt(pageInfo.attr("pageIndex"));
        dg.PageControl.PageSize = parseInt(pageInfo.attr("pageSize"));
        dg.PageControl.RecordCount = parseInt(pageInfo.attr("recordCount"));
        dg.PageControl.PageUrl = pageInfo.attr("pageUrl");

        var pageControlDiv = document.createElement("div");
        pageControlDiv.id = dg.controlId + "_pageControlsDiv";
        pageControlDiv.className = "pages";

        var totalRecordInfo = document.createElement("div");
        totalRecordInfo.className = "total";
        totalRecordInfo.innerHTML = "共 <span class=\"red\">" + dg.PageControl.RecordCount + "</span>条记录";
        pageControlDiv.appendChild(totalRecordInfo);
        
        //if (dg.PageControl.PageIndex > 0) 
        {
            var firstPageSpan = document.createElement("span");
            firstPageSpan.className = "pageback";
            var firstPageLink = document.createElement("a");
            firstPageLink.title = "首页";
            firstPageLink.innerHTML = "首页";
            firstPageLink.onclick = dg.PageControl.FirstPage;
            firstPageSpan.appendChild(firstPageLink);
            pageControlDiv.appendChild(firstPageSpan);
        }
        {
            var go10 = document.createElement("a");
            go10.title = "上十页";
            go10.className = "prev10";
            go10.innerHTML = "&nbsp;";
            go10.onclick = dg.PageControl.PrePageView;
            pageControlDiv.appendChild(go10);

            //if (dg.PageControl.PageIndex > 0) 
            {
                var prePage = document.createElement("a");
                prePage.title = "上一页";
                prePage.className = "prev";
                prePage.innerHTML = "&nbsp;";
                prePage.onclick = dg.PageControl.PrePage;
                pageControlDiv.appendChild(prePage);
            }
        }

        dg.PageControl.PageCount = parseInt(dg.PageControl.RecordCount / dg.PageControl.PageSize);
        if (dg.PageControl.PageCount * dg.PageControl.PageSize != dg.PageControl.RecordCount)
            dg.PageControl.PageCount++;
        dg.PageControl.PageViewCount = parseInt(dg.PageControl.PageCount / 10);
        if (dg.PageControl.PageViewCount * 10 != dg.PageControl.PageCount)
            dg.PageControl.PageViewCount++;

        var pageIndex = 0;
        for (var pageViewIndex = 0; pageViewIndex < dg.PageControl.PageViewCount; pageViewIndex++) {
            var pageViewContiner = document.createElement("div");
            var pageViewContinerAtt = document.createAttribute("_mark");
            pageViewContinerAtt.value = "pageViewContiner";
            pageViewContiner.attributes.setNamedItem(pageViewContinerAtt);
            pageViewContiner.style.display = "none";
            for (var i = 0; i < 10; i++) {
                if (pageIndex == dg.PageControl.PageIndex) {
                    var str = document.createElement("strong");
                    str.innerHTML = (pageIndex + 1);
                    pageViewContiner.appendChild(str);
                    pageViewContiner.style.display = "block";
                    dg.PageControl.CurrPageView = pageViewIndex;
                } else {
                    var pageLink = document.createElement("a");
                    pageLink.innerHTML = (pageIndex + 1);
                    var info = document.createAttribute("_page");
                    info.value = pageIndex;
                    pageLink.attributes.setNamedItem(info);
                    pageLink.onclick = dg.PageControl.PageIndexClick;
                    pageViewContiner.appendChild(pageLink);
                }
                pageIndex++;
                if (pageIndex >= dg.PageControl.PageCount) break;
            }
            pageControlDiv.appendChild(pageViewContiner);
        }
        {
            //if (dg.PageControl.PageIndex != dg.PageControl.PageCount - 1) 
            {
                var prePage = document.createElement("a");
                prePage.title = "下一页";
                prePage.className = "next";
                prePage.innerHTML = "&nbsp;";
                prePage.onclick = dg.PageControl.NextPage;
                pageControlDiv.appendChild(prePage);
            }

            var go10 = document.createElement("a");
            go10.title = "下十页";
            go10.className = "next10";
            go10.innerHTML = "&nbsp;";
            go10.onclick = dg.PageControl.NextPageView;
            pageControlDiv.appendChild(go10);
        }
        //if (dg.PageControl.PageIndex != dg.PageControl.PageCount - 1)
        {
            var firstPageSpan = document.createElement("span");
            firstPageSpan.className = "pageback";
            var firstPageLink = document.createElement("a");
            firstPageLink.title = "末页";
            firstPageLink.innerHTML = "末页";
            firstPageLink.onclick = dg.PageControl.LastPage;
            firstPageSpan.appendChild(firstPageLink);
            pageControlDiv.appendChild(firstPageSpan);
        }
        {
            var span = document.createElement("span");
            span.style.marginTop = -1;
            span.className = "pageback";
            span.innerHTML = "&nbsp;&nbsp;跳转&nbsp;";
            var pageCtl = document.createElement("input");
            pageCtl.type = "text";
            pageCtl.className = "fillPage";
            pageCtl.id = dg.controlId + "_customPageInput";
            pageCtl.value = (dg.PageControl.PageIndex + 1);
            span.appendChild(pageCtl);
            span.innerHTML += "&nbsp;&nbsp;";
            pageControlDiv.appendChild(span);

            var goLink = document.createElement("a");
            goLink.className = "go";
            goLink.title = "Go";
            goLink.onclick = dg.PageControl.GoPage;
            goLink.innerHTML = "GO";
            pageControlDiv.appendChild(goLink);
        }
        $("#" + dg.controlId).append(pageControlDiv);
    }

    dg.PageControl.FirstPage = function() {
        dg.PageControl.JunpPage(0);
    }

    dg.PageControl.PrePage = function() {
        dg.PageControl.JunpPage(dg.PageControl.PageIndex - 1);
    }

    dg.PageControl.PrePageView = function() {
        $("div[_mark='pageViewContiner']:eq(" + dg.PageControl.CurrPageView + ")").css("display", "none");
        dg.PageControl.CurrPageView--;
        if (dg.PageControl.CurrPageView < 0) dg.PageControl.CurrPageView = 0;
        $("div[_mark='pageViewContiner']:eq(" + dg.PageControl.CurrPageView + ")").css("display", "block");
    }

    dg.PageControl.NextPageView = function() {
        $("div[_mark='pageViewContiner']:eq(" + dg.PageControl.CurrPageView + ")").css("display", "none");
        dg.PageControl.CurrPageView++;
        if (dg.PageControl.CurrPageView >= dg.PageControl.PageViewCount) dg.PageControl.CurrPageView = dg.PageControl.PageViewCount - 1;
        $("div[_mark='pageViewContiner']:eq(" + dg.PageControl.CurrPageView + ")").css("display", "block");
    }

    dg.PageControl.NextPage = function() {
        dg.PageControl.JunpPage(dg.PageControl.PageIndex + 1);
    }

    dg.PageControl.LastPage = function() {
        dg.PageControl.JunpPage(dg.PageControl.PageCount - 1);
    }

    dg.PageControl.GoPage = function() {
        var page = $("#" + dg.controlId + "_customPageInput").val();
        if (isNaN(page)) {
            alert("请输入数字");
            $("#" + dg.controlId + "_customPageInput").val(dg.PageControl.PageIndex + 1);
            return;
        }
        var pageIndex = parseInt(page) - 1;
        dg.PageControl.JunpPage(pageIndex);
    }

    dg.PageControl.PageIndexClick = function() {
        var pageIndex = event.srcElement.attributes.getNamedItem("_page").value;
        dg.PageControl.JunpPage(pageIndex);
    }

    dg.PageControl.JunpPage = function(pageIndex) {
        if(isNaN(pageIndex))return;
        var page = parseInt(pageIndex);
        if(page < 0) page= 0;
        if(page > dg.PageControl.PageCount-1) page=  dg.PageControl.PageCount-1;        
        window.location.href = dg.PageControl.PageUrl + page;
    }
    //分页控件结束

    //创建空行
    dg.CreateEmptyRecord = function() {
        var lock = $("#" + dg.controlId + "_lockTableBody").find("tbody > tr");
        var scrollBody = $("#" + dg.controlId + "_scrollTableBody").find("tbody > tr");
        if (lock.size() >= dg.MinRowCount) return;     

        for (var i = lock.size(); i < dg.MinRowCount; i++) {
            //lock
            {
                var tdCount = $("#" + dg.controlId + "_lockTableBody").find("tbody > tr:first > td").size();
                var tr = document.createElement("tr");
                for (var index = 0; index < tdCount; index++) {
                    var td = document.createElement("td");
                    td.className = "norTr";
                    td.style.height = 23;
                    td.innerHTML = "&nbsp;";
                    tr.appendChild(td);
                }
                var lockBody = $("#" + dg.controlId + "_lockTableBody").find("tbody");
                lockBody.append(tr);
            }
            //scroll
            {
                var tdCount = $("#" + dg.controlId + "_scrollTableBody").find("tbody > tr:first > td").size();
                var tr = document.createElement("tr");
                for (var index = 0; index < tdCount; index++) {
                    var td = document.createElement("td");
                    td.innerHTML = "&nbsp;";
                    td.className = "norTr";
                    td.style.height = 23;
                    tr.appendChild(td);
                }
                var scrollBody1 = $("#" + dg.controlId + "_scrollTableBody").find("tbody");
                scrollBody1.append(tr);
            }
        }
    }

    //resize
    dg.ReSize = function(dataGridWidth) {
        if (!dg.LoadFinish) return;
        var d1 = new Date();

        var dataGrid = $("#" + dg.controlId);
        dataGrid.width(dataGridWidth);

        var tableBigHead = dataGrid.find(".tableBigHead");
        tableBigHead.width(dataGrid.width() - 2);
        var tableBody = dataGrid.find(".tableBody");
        tableBody.width(dataGrid.width() - 2);

        dg.setArrowIconVar();
        dg.RefreshArrowPoint();
        dg.scrollCellHeight();

        dg.debugMsg("ReSize Time:" + (new Date() - d1));
    }
    //
    return dg;
}